package com.ls.lserp.modules.purchase.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.utils.excel.template.ExcelTemplate;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.material.entity.MaterialStock;
import com.ls.lserp.modules.material.service.MaterialStockService;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.purchase.entity.PurchaseAdvance;
import com.ls.lserp.modules.purchase.entity.PurchaseContract;
import com.ls.lserp.modules.purchase.service.PurchaseContractService;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.service.SupplierService;
import com.ls.lserp.modules.sys.entity.Brand;
import com.ls.lserp.modules.sys.utils.DictUtils;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/purchase/contract/")
public class PurchaseContractController extends BaseController {

    //客户类别
    //甲方
    public static final Long OGNIZATION_TYPE_A = 9L;
    //乙方
    public static final Long OGNIZATION_TYPE_B = 4L;
    @Autowired
    private PurchaseContractService purchaseContractService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    Configuration freemarkerConfiguration;

    @ModelAttribute
    public PurchaseContract get(@RequestParam(required = false) String id) {

        // 判断id是否为空
        if (StringUtils.isNotBlank (id)) {

            // 执行查询语句 查询基本信息
            return purchaseContractService.findByID (Long.parseLong (id));
        } else {

            // 若为空，实例化
            return new PurchaseContract ();
        }
    }

    /**
     * 原辅料库存一览画面
     *
     * @return
     */
    @RequestMapping(value = {""})
    public String purchaseContract() {

        return "modules/purchase/purchaseContract";

    }

    /**
     * 拼接一览画面
     *
     * @param purchaseContract
     * @param request
     * @return response
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "purchaseContract");
        // 画面取得的检索项目
        String contractMaterialNO = purchaseContract.getContractMaterialNO ();
        String ognizationNameB = purchaseContract.getOgnizationNameB ();
        String dateStart = purchaseContract.getDateStart ();
        String dateEnd = purchaseContract.getDateEnd ();
        String ulSelected = purchaseContract.getUlSelected ();
        purchaseContract.setDeleteFlag ("0");
        if ("2".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_10";
            purchaseContract.setUlSelected (ulSelected);

        } else if ("1".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_20";
            purchaseContract.setUlSelected (ulSelected);

        } else if ("0".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_30";
            purchaseContract.setUlSelected (ulSelected);

        } else if ("5".equals (ulSelected)) {
            ulSelected = "AUDIT_STATUS-AUDIT_00";
            purchaseContract.setUlSelected (ulSelected);

        } else if ("4".equals (ulSelected)) {
            ulSelected = "-1";
            purchaseContract.setUlSelected (ulSelected);
            purchaseContract.setDeleteFlag ("1");
        } else if ("3".equals (ulSelected)) {
            ulSelected = "yunyun";
            purchaseContract.setUlSelected (ulSelected);

        }
        // 拼接字符串供分页使用
        String searchParam = "&contractMaterialNO=" + contractMaterialNO + "&ognizationNameB=" + ognizationNameB + "&dateStart=" + dateStart + "&dateEnd=" + dateEnd + "&ulSelected=" + ulSelected;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        //
        String contractFlag = purchaseContract.getContractFlag ();
        // 查询一览页面数据
        Page <PurchaseContract> page = purchaseContractService.findPurchaseContractList (new Page <PurchaseContract> (request, response),
                purchaseContract);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("contractList", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        map.put ("contractFlag", contractFlag);
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("purchaseContractList.ftl"), map);
        listMap.put ("purchaseContract", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }

    /**
     * 拼接供货商一览画面
     *
     * @param ognization
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"searchOgnizationList"})
    @ResponseBody
    public String searchOgnizationList(Ognization ognization, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "supplier");
        // 画面取得的检索项目
        String pCateCd = "";
        String pSupplierName = ognization.getOgnizationName ();
        Long ognizationType = ognization.getOgnizationType();
        if (ognizationType!=4) {
        	pCateCd = ognization.getOgnizationCategoryCd ();
		}
        // 拼接字符串供分页使用
        String searchParam = "&ognizationName=" + pSupplierName + "&ognizationCategoryCd=" + pCateCd+ "&ognizationType=" + ognizationType;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        //ognization.setOgnizationType(OGNIZATION_TYPE_B);
        ognization.setCurrentUser (ognization.getCurrentUser ());
        ognization.setPurchaseFlag("purchaseContract");
        // 查询一览页面数据
        Page <Ognization> page = supplierService.findList (new Page <Ognization> (request, response), ognization);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("supplierList", page.getList ());
        map.put ("pageNo", page.getPageNo ());
        map.put ("pageSize", page.getPageSize ());
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("supplierList.ftl"), map);
        listMap.put ("supplier", strHtml);
        listMap.put ("page", page.getHtml ());
        // ajax返回结果
        return renderString (response, listMap);
    }

    /**
     * 拼接原辅料一览画面
     *
     * @param purchaseContract
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"searchMaterialList"})
    @ResponseBody
    public String searchMaterialList(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                                     Model model) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "material");
        // 画面取得的检索项目
        String materialCode = purchaseContract.getMaterialCode ();
        String ognizationNameB = purchaseContract.getOgnizationNameB ();
        String materialTypeCD = purchaseContract.getMaterialTypeCD ();
        String customerContractNO = purchaseContract.getCustomerContractNO ();
        // 拼接字符串供分页使用
        String searchParam = "&materialCode=" + materialCode + "&ognizationNameB=" + ognizationNameB + "&materialTypeCD=" + materialTypeCD + "&customerContractNO=" + customerContractNO;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        List <PurchaseContract> materialList = purchaseContractService.searchMaterialList (purchaseContract);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("materialList", materialList);
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("materialList.ftl"), map);
        listMap.put ("material", strHtml);
        // ajax返回结果
        return renderString (response, listMap);
    }
    
    /**
     * 拼接原辅料一览画面
     *
     * @param purchaseContract
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"findMaterialList"})
    @ResponseBody
    public String findMaterialList(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                                     Model model) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "material");
        // 画面取得的检索项目
        String materialCode = purchaseContract.getMaterialCode ();
        Long ognizationId = purchaseContract.getOgnizationId();
        Long brandId = purchaseContract.getBrandId();
        String materialTypeCD = purchaseContract.getMaterialTypeCD ();
        // 拼接字符串供分页使用
        String searchParam = "&materialCode=" + materialCode + "&ognizationId=" + ognizationId + "&materialTypeCD=" + materialTypeCD+ "&brandId=" + brandId;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        List <PurchaseContract> materialList = purchaseContractService.findMaterialList (purchaseContract);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("materialList", materialList);
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("materialListMTM.ftl"), map);
        listMap.put ("material", strHtml);
        // ajax返回结果
        return renderString (response, listMap);
    }

    /**
     * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     *
     * @param filePath
     * @return html
     */
    public String readTxtFile(String filePath) {
        String strHtml = "";
        try {
            String encoding = "UTF-8";
            File file = new File (filePath);
            // 判断文件是否存在
            if (file.isFile ()) {
                InputStreamReader read = new InputStreamReader (
                        // 考虑到编码格式
                        new FileInputStream (file), encoding);
                BufferedReader bufferedReader = new BufferedReader (read);
                String lingText = null;
                while ((lingText = bufferedReader.readLine ()) != null) {
                    strHtml += lingText;
                }
                read.close ();
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
        return strHtml;
    }

    /**
     * 创建采购合同信息窗口
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"createContract"})
    public String createContract(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                                 Model model) {
        Ognization ognization = new Ognization ();
        ognization.setOgnizationType (OGNIZATION_TYPE_A);
        ognization = purchaseContractService.getPartyA (ognization);
        ognization.preInsert ();
        model.addAttribute ("ognization", ognization);
        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseContractCreate";
    }

    /**
     * 查看一条采购合同信息
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"viewContract"})
    public String viewContract(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                               Model model) {
    	List <PurchaseContract> materialList = new ArrayList<>();
        purchaseContract = purchaseContractService.getContract (purchaseContract);
        if ("PURCHASE_TYPE-10".equals(purchaseContract.getPurchaseType())) {
        	materialList = purchaseContractService.findMaterialByIdMTM (purchaseContract);
		}else if("PURCHASE_TYPE-20".equals(purchaseContract.getPurchaseType())){
			materialList = purchaseContractService.findMaterialByIdOrder (purchaseContract);
		}else{
            materialList = purchaseContractService.findMaterialByIdAlert(purchaseContract);
        }
        purchaseContract.setMaterialList (materialList);
        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseContractShow";
    }

    /**
     * 获取采购合同明细
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"findMaterial"})
    public String findMaterial(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                               Model model) {
        List <PurchaseContract> materialList = purchaseContractService.findMaterialByIdOrder (purchaseContract);
        purchaseContract.setMaterialList (materialList);
        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseAdvanceCreate";
    }

    /**
     * 编辑采购合同信息窗口
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"editContract"})
    public String editContract(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                               Model model) {
    	List <PurchaseContract> materialList = new ArrayList<>();
        purchaseContract = purchaseContractService.getContract (purchaseContract);
        if ("PURCHASE_TYPE-10".equals(purchaseContract.getPurchaseType())) {
        	materialList = purchaseContractService.findMaterialByIdMTM (purchaseContract);
		}else {
			materialList = purchaseContractService.findMaterialByIdOrder (purchaseContract);
		}
        purchaseContract.setMaterialList (materialList);
        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseContractCreate";
    }

    /**
     * 选择合同条款窗口
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"selectClause"})
    public String selectClause(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                               Model model) {

        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseContractCreate3";
    }

    /**
     * 获取合同条款
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"getClause"})
    @ResponseBody
    public String getClause(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                            Model model) {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        purchaseContract = purchaseContractService.getClause (purchaseContract);
        listMap.put ("contractClause", purchaseContract.getContractClause ());
        listMap.put ("clauseType", purchaseContract.getClauseType());
        return renderString (response, listMap);
    }

    /**
     * 乙方客户一览画面
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"ognizationList"})
    public String ognizationList(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                                 Model model) {
        if (purchaseContract.getOgnizationFlag () == 3) {
        	//getText ("ognization_common_fabricating")
            purchaseContract.setOgnizType ("加工厂");

        } else if (purchaseContract.getOgnizationFlag () == 4) {
        	//getText ("ognization_common_company")
            purchaseContract.setOgnizType ("公司");

        } else if (purchaseContract.getOgnizationFlag () == 5) {
        	//getText ("ognization_common_customer")
            purchaseContract.setOgnizType ("客户");

        }
        model.addAttribute ("purchaseContract", purchaseContract);
        return "modules/purchase/purchaseContractCreate2";
    }

    /**
     * 原辅料一览画面
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"materialList"})
    public String materialList(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                               Model model) {
    	List<Ognization> ogList = purchaseContractService.findOgnizationList();
        model.addAttribute ("purchaseContract", purchaseContract);
        model.addAttribute ("ogList", ogList);
        return "modules/purchase/purchaseContractCreate4";
    }
    
    /**
     * 原辅料一览画面
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"findBrandList"})
    @ResponseBody
    public String findBrandList(Long ognizationId, HttpServletRequest request, HttpServletResponse response) {
    	List<Brand> brList = purchaseContractService.findBrandList(ognizationId);
        return renderString (response, brList);
    }
    
    /**
     * 原辅料一览画面
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:edit")
    @RequestMapping(value = {"updateAlertStatus"})
    @ResponseBody
    public String updateAlertStatus(String[] materialIDStr,String ognizationIDB, HttpServletRequest request, HttpServletResponse response) {
    	purchaseContractService.updateAlertStatus(materialIDStr,ognizationIDB);
        return renderString (response, "");
    }
    
    /**
     * 查询面料是否已创建采购
     *
     * @return
     */
    @RequiresPermissions("purchase:contract:edit")
    @RequestMapping(value = {"checkMaterial"})
    @ResponseBody
    public String checkMaterial(String materialIdStr,String purchaseType,String ognizationIDB, HttpServletRequest request, HttpServletResponse response) {
    	String returnStr = purchaseContractService.checkMaterial(materialIdStr,purchaseType,ognizationIDB);
        return renderString (response, returnStr);
    }
    
    /**
     * 创建编辑保存仓库信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:contract:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                       Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (purchaseContract.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            PurchaseContract purchaseContractNew = get (purchaseContract.getId ().toString ());
            // 判断数据是否删除
            if (purchaseContractNew == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseContractNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (purchaseContract.getVersion () == get (purchaseContract.getId ().toString ()).getVersion ()) {

                // 版本号加1
                purchaseContract.setVersion (purchaseContract.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }


        // 保存数据
        purchaseContractService.savePurchaseContract (purchaseContract);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 提交采购预付款信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:contract:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (purchaseContract.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            PurchaseContract purchaseContractNew = get (purchaseContract.getId ().toString ());
            // 判断数据是否删除
            if (purchaseContractNew == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseContractNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (purchaseContract.getVersion () == get (purchaseContract.getId ().toString ()).getVersion ()) {

                // 版本号加1
                purchaseContract.setVersion (purchaseContract.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }


        // 保存数据
        purchaseContractService.deletePurchaseContract (purchaseContract);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 提交采购预付款信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:contract:edit")
    @RequestMapping(value = "commit")
    @ResponseBody
    public String commit(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                         Model model) throws ResourceException {

        // 判断id是否为null （判断新建或修改）
        if (purchaseContract.getId () != null) {
            // 编辑数据
            // 判断数据是否删除
            PurchaseContract purchaseContractNew = get (purchaseContract.getId ().toString ());
            // 判断数据是否删除
            if (purchaseContractNew == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseContractNew.getDeleteFlag ())) {
                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }

            // 排他处理
            if (purchaseContract.getVersion () == get (purchaseContract.getId ().toString ()).getVersion ()) {

                // 版本号加1
                purchaseContract.setVersion (purchaseContract.getVersion () + 1);
            } else {

                // 返回提示信息
                return renderString (response, AjaxDone.error (getText ("warehouse_edit_save_msg_fail")));
            }
        }

        // 保存数据
        purchaseContractService.commitPurchaseContract (purchaseContract);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("warehouse_edit_save_msg_success")));


    }

    /**
     * 审核页面
     *
     * @param purchaseContract
     * @param model
     * @return
     */
    @RequiresPermissions("purchase:contract:audit")
    @RequestMapping(value = "audit")
    public String audit(PurchaseContract purchaseContract, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

        // 履历一览取得
        AuditInfo auditInfo = new AuditInfo ();
        // id
        auditInfo.setAuditRelateId (purchaseContract.getId ());
        // 阶段
        auditInfo.setAuditPhaseCd (ResourcesUtil.getConfig ("audit_phase_purchase"));
        AuditInfo resultInfo = purchaseContractService.findAuditInfo (auditInfo);


        resultInfo.setAuditRelateId (purchaseContract.getId ());

        resultInfo.setAuditRelateNo (purchaseContract.getContractMaterialNO ());

        resultInfo.setAuditPhaseCd (ResourcesUtil.getConfig ("audit_phase_purchase"));

        // 将实体类值赋给mvc model层返回jsp页面
        model.addAttribute ("auditInfo", resultInfo);

        // 返回页面地址
        return "modules/order/auditInfo";
    }

    /**
     * 保存履历信息
     *
     * @param auditInfo
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException
     */
    @RequiresPermissions("purchase:advance:edit")
    @RequestMapping(value = "saveAudit")
    @ResponseBody
    public String saveAudit(AuditInfo auditInfo, HttpServletRequest request, Model model, HttpServletResponse response, HttpSession session) throws ResourceException {

        // 是否需要更新样品需求状态
        boolean isUpdateStatus = false;

        // 判断数据是否删除
        PurchaseContract purchaseContract = get (Long.toString (auditInfo.getAuditRelateId ()));
        // 判断数据是否删除
        if (purchaseContract.getContractMaterialNO () == null || BaseEntity.DEL_FLAG_DELETE.equals (purchaseContract.getDeleteFlag ())) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }

        // 审核结果已经通过,返回错误提示信息
        AuditInfo pAuditResult = new AuditInfo ();
        pAuditResult.setAuditPhaseCd (auditInfo.getAuditPhaseCd ());
        pAuditResult.setAuditRelateId (auditInfo.getAuditRelateId ());
        if (purchaseContractService.getAuditResult (pAuditResult) > 0) {
            // 返回提示信息
            return renderString (response, AjaxDone.error (getText ("This_record_has_been_deleted_or_modified_the_operation_failed")));
        }


        // 保存样品数据
        purchaseContractService.saveAuditInfo (auditInfo, isUpdateStatus);

        // 保存成功返回提示信息
        return renderString (response, AjaxDone.ok (SystemMessageUtils.getMessageName ("audit_ok_msg")));

    }
    /**
     * 拼接原辅料一览画面
     *
     * @param purchaseContract
     * @return
     */
    @RequiresPermissions("purchase:contract:view")
    @RequestMapping(value = {"findMaterialAlertList"})
    @ResponseBody
    public String findMaterialAlertList(PurchaseContract purchaseContract, HttpServletRequest request, HttpServletResponse response,
                                   Model model) throws Exception {
        Map <Object, Object> listMap = new HashMap <Object, Object> ();
        // ajax回调时使用的一览list名
        request.setAttribute ("listNames", "material");
        // 画面取得的检索项目
   /*     String materialCode = purchaseContract.getMaterialCode ();
        Long ognizationId = purchaseContract.getOgnizationId();
        Long brandId = purchaseContract.getBrandId();
        String materialTypeCD = purchaseContract.getMaterialTypeCD ();*/
        // 拼接字符串供分页使用
        //String searchParam = "&materialCode=" + materialCode + "&ognizationId=" + ognizationId + "&materialTypeCD=" + materialTypeCD+ "&brandId=" + brandId;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        //request.setAttribute (Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        List <PurchaseContract> materialList = purchaseContractService.findMaterialAlertList(purchaseContract);
        // 读取文件生成字符串
        String strUri = request.getContextPath () + Global.getAdminPath ();
        String strHtml = "";
        Map <String, Object> map = new HashedMap ();
        map.put ("adminUri", strUri);
        map.put ("materialList", materialList);
        strHtml = FreeMarkerTemplateUtils
                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("inventoryControllAlertFtl.ftl"), map);
        listMap.put ("material", strHtml);
        // ajax返回结果
        return renderString (response, listMap);
    }
    @RequiresPermissions("purchase:contract:edit")
	@ResponseBody
	@RequestMapping(value = "exportFile")
	public String exportFile(PurchaseContract purchaseContract ,HttpServletResponse response){
		try {
            // 模版
            String basePath = SystemPath.getClassPath();
            String tempFilePath = "";
            if ("1".equals(purchaseContract.getClauseType()) ) {
            	// 第一种合同
            	if ("定制采购".equals(purchaseContract.getPurchaseType()) ) {
            		tempFilePath = "/" + basePath + "purchaseContract01.xlsx";
            	} else {
            		tempFilePath = "/" + basePath + "purchaseContract03.xlsx";
            	}
            } else if ("4".equals(purchaseContract.getClauseType()) ) {
            	// 第二种合同
            	if ("定制采购".equals(purchaseContract.getPurchaseType()) ) {
            		tempFilePath = "/" + basePath + "purchaseContract05.xlsx";
            	} else {
            		tempFilePath = "/" + basePath + "purchaseContract06.xlsx";
            	}
            } else {
            	// 第三种合同
            	if ("定制采购".equals(purchaseContract.getPurchaseType()) ) {
            		tempFilePath = "/" + basePath + "purchaseContract02.xlsx";
            	} else {
            		tempFilePath = "/" + basePath + "purchaseContract04.xlsx";
            	}
            }
            ExcelTemplate handle = this.purchaseContractService.export(purchaseContract, tempFilePath);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + purchaseContract.getContractMaterialNO()  +".xlsx");
            OutputStream os = response.getOutputStream();
            // 写到输出流并关闭资源
            handle.writeAndClose(tempFilePath, os);
            os.flush();
            os.close();
            handle.readClose(tempFilePath);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
	}
}
